const {
  queryUserListByCondition,
  queryMaintainerListByAssetsId
} = require('../../api/workOrder')
const {
  USER_TYPE
} = require('../../constant/index')
const {
  getUserType
} = require('../../utils/strorage')
const {
  clearEmptyKey
} = require('../../utils/clearEmptyKey')
const {
  to,
  openLoading,
  closeLoading
} = getApp()
Page({
  data: {
    loadingType: '',
    dataList: [],
    searchAreaValues: {},
    pagination: {
      page: 1,
      limit: 10
    },
    total: 0
  },

  onLoad() {
    this.resetData()
    this.getSysUserList()
  },

  async getSysUserList(openL = true) {
    const optionsData = {};
    const {
      companyId
    } = this.options
    if (companyId) {
      optionsData.companyId = companyId
    }

    const {
      searchAreaValues
    } = this.data
    const params = {
      queryCondition: searchAreaValues.inputVal || '',
      ...optionsData,
      ...this.data.pagination
    }

    clearEmptyKey(params)
    openL && openLoading()
    const [err, data] = await to(queryUserListByCondition(params))
    closeLoading()
    if (!err) {
      const {
        dataList
      } = this.data
      this.setData({
        dataList: dataList.concat(data.dataList),
        total: data.total
      })

      if (data.total === 0) {
        this.setData({
          loadingType: 'empty'
        })
        return
      }

      if (this.data.dataList.length >= data.total) {
        this.setData({
          loadingType: 'end'
        })
      }
    }
  },

  handleScrolltolower() {
    const {
      total,
      pagination,
      dataList
    } = this.data

    if (dataList.length < total) {
      let page = pagination.page;
      page++
      this.setData({
        loadingType: 'loading',
        ['pagination.page']: page
      })
      this.getSysUserList(false)
    }
  },


  resetData() {
    this.setData({
      ['pagination.page']: 1,
      dataList: [],
      loadingType: '',
      total: 0
    })
  },

  handleSearchChange(event) {
    this.setData({
      searchAreaValues: event.detail,
    })
    this.resetData()
    this.getSysUserList()
  },

  handleChoose(event) {
    const currentData = event.detail
    const pages = getCurrentPages()
    const parentPage = pages[pages.length - 2];
    parentPage.setUserData({
      ['formData.launchUserId']: currentData.userId,
      ['formData.launchUserName']: currentData.userName,
      ['formData.companyId']: currentData.companyId,
      ['formData.companyName']: currentData.companyName,
      ['formData.departmentId']: currentData.departmentId,
      ['formData.departmentName']: currentData.departmentName,
    })

    wx.navigateBack()
  }
})